<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const obj = {
            uname: 'ikun',
            hobby: ['sing', 'dance', 'rap'],
            age: '2.5',
            fans: {
                uname: '小黑子',
                active: '露出了鸡脚'
            },
            success: undefined
        }

        // let newObj = obj

        // console.log(newObj.uname);

        let newObj = {}
        //1.for in 方法浅拷贝
        // for (let key in obj) {
        //     newObj[key] = obj[key]
        //     // newObj.key = obj.key
        // }

        //2.Object.assign 方法浅拷贝
        // Object.assign(newObj, obj)

        //3.展开运算符方法浅拷贝
        // newObj = { ...obj }


        //1.JSON方法实现深拷贝

        // newObj = JSON.parse(JSON.stringify(obj))

        //2.递归深拷贝

        function deepClone (newObj, oldObj) {
            for (let key in oldObj) {
                //判断这一项是否为数组，是数组的话继续调用deepClone函数遍历，直到不是复杂数据类型为止
                if (oldObj[key] instanceof Array) {
                    newObj[key] = []
                    deepClone(newObj[key], oldObj[key])
                }
                //判断这一项是否为对象，是对象的话继续调用deepClone函数遍历，直到不是复杂数据类型为止
                else if (oldObj[key] instanceof Object) {
                    newObj[key] = {}
                    deepClone(newObj[key], oldObj[key])
                }
                //实现终极目标,一定要放到分支语法当中不然前功尽弃
                else {
                    newObj[key] = oldObj[key]
                }
            }
        }

        deepClone(newObj, obj)

        console.log(newObj);
        newObj.hobby[1] = '背带裤'
        console.log(obj);
    </script>
</body>

</html>